import { Reducer } from 'redux';
import { Effect } from 'dva';
import { ArticleType } from '@/domains/article';
import { queryArticle, queryArticleList } from './service';

export interface StateType {
  articleList: ArticleType[];
  article: ArticleType | null;
}

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetchArticleList: Effect;
    fetchArticle: Effect;
  };
  reducers: {
    save: Reducer;
    clearArticle: Reducer;
  };
}

const model: ModelType = {
  namespace: 'articleContent',

  state: {
    articleList: [],
    article: null,
  },

  effects: {
    *fetchArticleList({ payload, callback }, { call, put }) {
      const articleList = yield call(queryArticleList, payload);
      if (articleList && articleList.length) {
        yield put({ type: 'save', payload: { articleList } });
        callback && callback();
      }
    },
    *fetchArticle({ payload, callback }, { call, put }) {
      const article = yield call(queryArticle, payload);
      if (article && article.time) {
        yield put({ type: 'save', payload: { article } });
        callback && callback();
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
    clearArticle(state) {
      return { ...state, article: null };
    },
  },
};

export default model;
